import api from './api'
import storage from "./storage";
import config from './config'
import crypto from './crypto'
import setting from '@/qly/setting'

// 获取微信登录code
export function getWechatCode() {
    return new Promise((resolve, reject) => {
        uni.login({success: resolve, fail: reject})
    })
}

// 登录成功后统一执行
export async function handleLoginResult(result) {
    if (result.success) {
        storage.set(storage.token, result.data)
        storage.set(storage.login, true)
        const res = await api.auth.info()
        if (res.success) {
            // 设置语言
            i18n.global.locale = res.data.config.language
            // 修改uni-app语言
            // uni.setLocale(res.data.config.language == 'en_US' ? 'en' : 'zh-Hans')
            uni.setLocale('zh-Hans')
            storage.set(setting.LS_APP_LANG, res.data.config.language)
            
            storage.set(storage.user, res.data)
        }
        return res
    } else {
        return result
    }
}

// 微信预登陆方法
export async function prepareWechatLogin(next) {
    const res = await wechatCodeLogin()
    const login = () => {
        next(res)
    }
    const register = async mobileEvent => {
        const codeEvent = await getWechatCode()
        const data = {code: codeEvent.code, mobileCode: mobileEvent.detail.code}
        const result = await api.auth.mobileAuth(data)
        if (result.success) {
            const res = await wechatCodeLogin()
            next(res)
        } else {
            next(result)
        }
    }
    if (res.success) {
        return {login}
    } else {
        return {register}
    }
}

// 获取用户信息
export function getUserInfo() {
    return storage.storageRef(storage.user)
}

// 刷新用户信息
export async function refreshUserInfo() {
    const userInfo = storage.storageRef(storage.user)
    const res = await api.auth.info()
    if (res.success) {
        userInfo.value = res.data
    }
}

// 使用微信code登录
export async function wechatCodeLogin() {
    const event = await getWechatCode()
    const result = await api.auth.wechatLogin(event.code)
    return handleLoginResult(result)
}

// 密码加密
export function encryptPassword(password) {
    return crypto.AES.encrypt(password, config.aesKey, config.aesIv)
}

// 是否登录
export function isLogin() {
    return storage.get(storage.login, false)
}

// 登出
export async function logout() {
    const result = await api.auth.logout()
    if (result.success) {
        clearLoginInfo()
    }
}

// 清空登录信息
export function clearLoginInfo() {
    storage.del(storage.login)
    storage.del(storage.token)
    storage.del(storage.user)
}


